import connection from '@ohos.net.connection';
import { BusinessError } from '@ohos.base';
import { promptAction } from '@kit.ArkUI'
/**
 *判断是否有网络
 *
 */
class NetworkStatusUtil{

  public  isNetworkStatus (){
    let netSpecifier: connection.NetSpecifier = {
      netCapabilities: {
        // 假设当前默认网络是WiFi，需要创建蜂窝网络连接，可指定网络类型为蜂窝网
        bearerTypes: [connection.NetBearType.BEARER_CELLULAR,
          connection.NetBearType.BEARER_WIFI,
          connection.NetBearType.BEARER_ETHERNET],
        // 指定网络能力为Internet
        networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET]
      },
    };
    // 指定超时时间为10s(默认值为0)
    let timeout = 10 * 1000;

    // 创建NetConnection对象
    let conn = connection.createNetConnection(netSpecifier, timeout);
    // 订阅指定网络状态变化的通知
    conn.register((err: BusinessError, data: void) => {
      // 订阅事件，如果当前指定网络可用，通过on_netAvailable通知用户
      conn.on('netAvailable', ((data: connection.NetHandle) => {
        promptAction.showToast({message:`网络可用`})
      }));

      // 订阅事件，如果当前指定网络不可用，通过on_netUnavailable通知用户
      conn.on('netUnavailable', ((data: void) => {
        promptAction.showToast({message:`网络不可用`})
      }));
    });
  }


  /**
   * 检查网络是否连接
   * @returns {Promise<boolean>} - 网络可用时解析为 true，网络不可用时拒绝
   */
  async checkNetworkStatus(): Promise<void> {
    return new Promise((resolve, reject) => {
      let netSpecifier: connection.NetSpecifier = {
        netCapabilities: {
          bearerTypes: [
            connection.NetBearType.BEARER_CELLULAR,
            connection.NetBearType.BEARER_WIFI,
            connection.NetBearType.BEARER_ETHERNET
          ],
          networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET]
        }
      };
      let timeout = 10 * 1000;
      let conn = connection.createNetConnection(netSpecifier, timeout);

      conn.register((err: BusinessError, data: void) => {
        if (err) {
          reject(err);
          return;
        }

        conn.on('netAvailable', (data: connection.NetHandle) => {
          resolve();
        });

        conn.on('netUnavailable', (data: void) => {
          reject(new Error('网络不可用'));
        });
      });
    });
  }
}
const networkStatusUtil = new NetworkStatusUtil()

export default networkStatusUtil as NetworkStatusUtil
